<template>
  <canvas class="valid-code" @click="refreshCode" ref="canvasRef" />
</template>

<script setup>
import { ref, onMounted, nextTick, defineEmits } from 'vue';

const emit = defineEmits(['update:code']);
const canvasRef = ref(null);
const code = ref('');
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const codeLength = 4;

const generateCode = () => {
  let result = '';
  for (let i = 0; i < codeLength; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  code.value = result;
  console.log('触发事件，验证码:', result);
  emit('update:code', result);
  drawCode();
};

const refreshCode = () => {
  generateCode();
};

const drawCode = () => {
  nextTick(() => {
    const canvas = canvasRef.value;
    if (!canvas) return;
    
    // 设置画布尺寸（解决高清屏模糊问题）
    const displayWidth = canvas.offsetWidth;
    const displayHeight = canvas.offsetHeight;
    canvas.width = displayWidth;
    canvas.height = displayHeight;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    // 清空画布
    ctx.clearRect(0, 0, displayWidth, displayHeight);
    
    // 设置背景色
    ctx.fillStyle = '#f5f7fa';
    ctx.fillRect(0, 0, displayWidth, displayHeight);
    
    // 绘制干扰线
    for (let i = 0; i < 5; i++) {
      ctx.strokeStyle = `rgba(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 255}, 0.5)`;
      ctx.beginPath();
      ctx.moveTo(Math.random() * displayWidth, Math.random() * displayHeight);
      ctx.lineTo(Math.random() * displayWidth, Math.random() * displayHeight);
      ctx.stroke();
    }
    
    // 绘制干扰点
    for (let i = 0; i < 30; i++) {
      ctx.fillStyle = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.5)`;
      ctx.beginPath();
      ctx.arc(Math.random() * displayWidth, Math.random() * displayHeight, 1, 0, 2 * Math.PI);
      ctx.fill();
    }
    
    // 绘制验证码文本
    ctx.font = 'bold 24px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    for (let i = 0; i < code.value.length; i++) {
      const char = code.value.charAt(i);
      const x = displayWidth / (code.value.length + 1) * (i + 1);
      const y = displayHeight / 2;
      
      const rotate = (Math.random() - 0.5) * 0.4;
      ctx.save();
      ctx.translate(x, y);
      ctx.rotate(rotate);
      ctx.fillStyle = `rgb(${Math.random() * 100 + 50}, ${Math.random() * 100 + 50}, ${Math.random() * 100 + 50})`;
      ctx.fillText(char, 0, 0);
      ctx.restore();
    }
  });
};

onMounted(() => {
  generateCode();
});
</script>

<style scoped>
.valid-code {
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  user-select: none;
  background-color: #f5f7fa;
  display: block; /* 确保canvas正确显示 */
}
</style>